﻿using Com.Lancetinc.Evs.Data;
using Com.Lancetinc.Evs.Data.Domain;
using Com.Lancetinc.Evs.Helpers;
using Com.Lancetinc.Evs.Reports;
using Com.Lancetinc.Evs.Services;
using Com.Lancetinc.Evs.ViewModels;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace Com.Lancetinc.Evs.Windows
{
    /// <summary>
    /// 报告编辑页面
    /// </summary>
    public partial class ReportEditWindow
    {
        private ExperViewModel _experVm;
        private bool _changed = false;

        public ReportEditWindow()
        {
            ThemeHelper.ChangeThemeToDark(this);

            InitializeComponent();
            var rc = SystemParameters.WorkArea;
            Width = Math.Min(rc.Width, 1440);
            Height = Math.Min(rc.Height, 960);
            GridTitle.MouseDown += GridTitle_MouseDown;
            this.Closing += ReportEditWindow_Closing;

#if DEBUG
            this.ResizeMode = ResizeMode.CanResize;
            this.WindowStyle = WindowStyle.None;
            this.UseNoneWindowStyle = false;
#endif
        }

        public static void Show(string seqNo)
        {
            var exper = AppRepositories.Exper.FindBySeqNo(seqNo);
            Show(new ExperViewModel(exper));
        }

        public static void Show(ExperViewModel exper)
        {
            var win = new ReportEditWindow
            {
                Owner = Application.Current.MainWindow,
                _experVm = exper
            };
            win.ShowDialog();
        }

        private ReportViewModel _reportVm;
        private Exper _experBk = null;
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            _reportVm = new ReportViewModel(_experVm);
            CtrlRpt.Setup(_reportVm, ReportTemplateUsage.Edit);
            ctrlPatient.DataContext = _experVm;

            ctrlPatient.CanDelete = true;
            ctrlPatient.CanPrint = true;
            ctrlPatient.RequirePrint += CtrlPatient_RequirePrint;
            _experBk = BeanUtil.Clone(_experVm.Exper);

            var experInfo = ExperManager.Default.WrapHistoryExper(_experVm);
            CtrlReportImagePreview.Setup(experInfo);

            CtrlVideo.SetExper(experInfo);
        }

        private void ReportEditWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            // _experVm == null表示被删除
            if (_experVm is { IsReadonly: false })
            {
                try
                {
                    if (!BeanUtil.AreEqual(_experBk, _experVm.Exper))
                    {
                        AppRepositories.Exper.Save(_experVm.Exper);
                        _changed = true;
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
            }

            this.DialogResult = _changed;
        }

        private void GridTitle_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            this.DragMove();
        }

        private void CtrlPatient_OnExperDeleted(object sender, EventArgs e)
        {
            _changed = true;
            _experVm.SeqNo = null;
            _experVm = null;
            Close();
        }

        private async void CtrlPatient_RequirePrint(object sender, EventArgs e)
        {
            await CtrlRpt.Print();
        }

        private void CtrlPatient_OnSaveSucceed(object sender, EventArgs e)
        {
            _experBk = BeanUtil.Clone(_experVm.Exper);
            _changed = true;
        }

        private void CtrlRpt_OnReportPrinted(object sender, EventArgs e)
        {
            _experBk = BeanUtil.Clone(_experVm.Exper);
            _changed = true;
        }

        /// <summary>
        /// 插入图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CtrlReportImagePreview_OnImageSelected(object sender, string e)
        {
            CtrlRpt.InsertImage(e);
        }

        /// <summary>
        /// 术语选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ReportTermsUserControl_OnTermSelected(object sender, string e)
        {
            CtrlRpt.InsertTerm(e);
        }

        private List<ColumnDefinition> _columnDefs;
        /// <summary>
        /// 全屏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="isFullScreen"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void CtrlVideo_OnOnFullScreenChanged(object sender, bool isFullScreen)
        {
            if (isFullScreen)
            {
                // 备份各列定义
                if (_columnDefs == null)
                {
                    _columnDefs = new List<ColumnDefinition>();
                    foreach (var def in GridMain.ColumnDefinitions)
                    {
                        _columnDefs.Add(new ColumnDefinition
                        {
                            Width = def.Width
                        });
                    }
                }

                foreach (var def in GridMain.ColumnDefinitions.Take(GridMain.ColumnDefinitions.Count - 1))
                {
                    def.Width = new GridLength(0);
                }
                return;
            }
            if (_columnDefs == null)
                return;

            for (int i = 0; i < _columnDefs.Count; i++)
            {
                GridMain.ColumnDefinitions[i].Width = _columnDefs[i].Width;
            }
        }

        private double _colTermsWidthBk = -1;
        /// <summary>
        /// 点击显示/隐藏 常用术语
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnHideTerms_OnClick(object sender, RoutedEventArgs e)
        {
            var m = BtnHideTerms.Margin;
            if (_colTermsWidthBk <= 0)
            {
                _colTermsWidthBk = ColTerms.Width.Value;
                ColTerms.Width = GridLength.Auto;
                CtrlReportTermsUser.Visibility = Visibility.Collapsed;
                CtrlReportImagePreview.Visibility = Visibility.Collapsed;
                BtnHideTerms.Content = ">>";

                BtnHideTerms.Margin = new Thickness(m.Left, m.Top, 0, m.Bottom);
                return;
            }

            ColTerms.Width = new GridLength(_colTermsWidthBk, GridUnitType.Pixel);
            CtrlReportTermsUser.Visibility = Visibility.Visible;
            CtrlReportImagePreview.Visibility = Visibility.Visible;
            BtnHideTerms.Content = "<<";
            BtnHideTerms.Margin = new Thickness(m.Left, m.Top, 20, m.Bottom);
            _colTermsWidthBk = -1;
        }

        private void CtrlVideo_OnOnCannotDisplayFully(object sender, EventArgs e)
        {
            BtnHideTerms_OnClick(null, null);
        }
    }
}